<template>
  <div class="page">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button
              class="back-btn"
              :icon="ArrowLeft"
              @click="handleBack">返回</el-button>
            <el-button
              class="add-btn"
              type="primary"
              @click="openDialog('add', null)">新增成绩</el-button>
            <div class="info-group">
              <span class="total-count">共计{{ total }}条</span>
              <span class="total-class">班级：{{ clazzDetailStore.clazz_name }}</span>
              <span class="student-name">{{ student_name }}</span>
            </div>
          </div>
          <div class="right">
            <el-form inline @submit.prevent>
              <el-form-item label="科目">
                <el-input
                  v-model="searchForm.course"
                  placeholder="请输入科目"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="Search"
                  @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="clientData"
        style="width: 100%"
        empty-text="暂无数据"
        :table-layout="tableLayout">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="course" label="科目" />
        <el-table-column prop="value" label="分数" />
        <el-table-column prop="teacher" label="教师" />
        <el-table-column label="操作" width="180">
          <template #default="data">
            <div class="icon-group">
              <el-tooltip effect="light" content="编辑" placement="top">
                <el-button
                  icon="Edit"
                  type="primary"
                  @click="openDialog('edit', data.row.id)" />
              </el-tooltip>

              <el-tooltip effect="light" content="删除" placement="top">
                <el-button
                  icon="Delete"
                  type="danger"
                  @click="handleDelete(data.row.id)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        background
        layout="total,  prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogFormTitle">
      <el-form ref="formRef" :model="dialogForm">
        <el-form-item label="科目" label-width="140px" prop="course">
          <el-input v-model="dialogForm.course" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分数" label-width="140px" prop="value">
          <el-input
            v-model="dialogForm.value"
            autocomplete="off"
            type="number"
            min="0"
            max="100" />
        </el-form-item>
        <el-form-item label="教师" label-width="140px" prop="teacher">
          <el-input v-model="dialogForm.teacher" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(dialogFormTitle === '新增成绩' ? 'add' : 'edit')">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useClazzDetailStore } from '../../stores/clazz'
import { getStudentDetail } from '@/api/student'
import { useRouter } from 'vue-router'
import { useStudentDetailStore } from '@/stores/student'
import { ref, computed, onMounted, reactive } from 'vue'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deleteGrade, addGrade, updateGrade } from '@/api/score'
const studentDetailStore = useStudentDetailStore()
const clazzDetailStore = useClazzDetailStore()

const router = useRouter()
// 总条数
const total = ref(0)
// 表格布局
const tableLayout = ref('fixed')
// 表格当前的显示数据
const clientData = ref([])
// 存储所有数据用于本地分页
const allData = ref([])
// 当前页数
const current = ref(1)
// 每页的显示条数
const pageSize = ref(10)
// 表格加载状态
const loading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)

// 搜索相关
const searchForm = reactive({
  course: ''
})

// 对话框标题
const dialogFormTitle = ref('')
// 对话框表单数据
const dialogForm = reactive({
  course: '',
  value: '',
  teacher: ''
})

// 表单元素
const formRef = ref(null)
const student_name = ref('')

// 获取学生ID
const student_id = computed(() => studentDetailStore.student_id)

// 数据加载
const loadData = async () => {
  loading.value = true
  try {
    const res = await getStudentDetail(student_id.value)
    if (res.status === 200) {
      student_name.value = res.data.info.name || '未知'
      allData.value = res.data.info.grades || []
      applyLocalSearchAndPagination()
    }
    loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage.error(error.message || '获取学生详情失败')
  }
}

// 本地搜索和分页函数
const applyLocalSearchAndPagination = () => {
  let filteredData = allData.value

  // 本地搜索过滤
  if (searchForm.course.trim()) {
    filteredData = filteredData.filter((item) =>
      item.course.toLowerCase().includes(searchForm.course.toLowerCase())
    )
  }

  // 设置总数
  total.value = filteredData.length

  // 本地分页
  const start = (current.value - 1) * pageSize.value
  const end = start + pageSize.value
  clientData.value = filteredData.slice(start, end)
}

const handleCurrentChange = (value) => {
  current.value = value
  applyLocalSearchAndPagination()
}

const handleSizeChange = (value) => {
  pageSize.value = value
  current.value = 1
  applyLocalSearchAndPagination()
}

// 搜索处理函数
const handleSearch = () => {
  current.value = 1 // 搜索时重置到第一页
  applyLocalSearchAndPagination()
}

// 重置搜索
const resetSearch = () => {
  searchForm.course = ''
  current.value = 1
  applyLocalSearchAndPagination()
}

const handleBack = () => {
  router.push('/clazzDetail')
}

// 删除处理函数
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条成绩数据吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 删除后端数据
    await deleteGrade(id)

    // 从本地数据中删除
    const index = allData.value.findIndex((item) => item.id === id)
    if (index > -1) {
      allData.value.splice(index, 1)
    }

    // 智能分页处理 - 当删除当前页最后一条数据时，自动跳转到上一页
    if (current.value > 1 && clientData.value.length === 1) {
      current.value--
    }

    ElMessage.success('删除成功!')

    // 重新应用本地搜索和分页
    applyLocalSearchAndPagination()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('删除操作已取消')
    } else {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 打开对话框
const openDialog = (model, id) => {
  dialogFormTitle.value = model === 'add' ? '新增成绩' : '编辑成绩'
  dialogForm.id = id
  if (model === 'add') {
    dialogForm.student_id = student_id.value
    dialogForm.course = ''
    dialogForm.value = ''
    dialogForm.teacher = ''
  } else {
    // 编辑模式，根据ID从本地数据中查找并填充表单
    const item = allData.value.find((item) => item.id === id)
    if (item) {
      // 编辑不需要学生ID  需要成绩id
      dialogForm.course = item.course
      dialogForm.value = item.value
      dialogForm.teacher = item.teacher
    }
  }
  dialogVisible.value = true
}

const submitForm = async (model) => {
  try {
    await formRef.value.validate()
    if (model === 'add') {
      await addGrade(dialogForm)
      ElMessage.success('新增成功!')
    } else {
      // 编辑成绩逻辑
      await updateGrade(dialogForm.id, {
        course: dialogForm.course,
        value: dialogForm.value,
        teacher: dialogForm.teacher
      })
      ElMessage.success('编辑成功!')
    }
    dialogVisible.value = false
    // 刷新数据
    loadData()
    applyLocalSearchAndPagination()
  } catch (error) {
    ElMessage.error(error.message || '操作失败，请重试')
  }
}

onMounted(() => {
  if (student_id.value) {
    loadData()
  } else {
    ElMessage.warning('未选择学生，请从班级详情页面进入')
    router.push('/clazzDetail')
  }
})

</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    gap: 15px;

    .info-group {
        display: flex;
        align-items: center;
        gap: 8px;

        .total-count {
          font-size: 0.7rem;
          font-weight: 500;
          color: #606266;
          background: #f5f7fa;
          padding: 2px 8px;
          border-radius: 2px;
        }

        .total-class {
          font-size: 0.7rem;
          font-weight: 500;
          color: #606266;
          background: #f0f9ff;
          padding: 2px 8px;
          border-radius: 2px;
        }

        .student-name {
          font-size: 0.7rem;
          font-weight: 500;
          color: #606266;
          background: #fdf6ec;
          padding: 2px 8px;
          border-radius: 2px;
        }
      }
  }

  .right {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.icon-group {
  display: flex;
  gap: 8px;

  .el-button {
    padding: 4px 8px;
  }
}
</style>
